<template>
  <div class="favorites-page">
    <div class="container-custom py-8">
      <h1 class="text-3xl font-bold mb-8">我的收藏</h1>
      
      <div v-if="pending" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div v-for="i in 6" :key="i" class="card animate-pulse">
          <div class="h-48 bg-gray-200" />
          <div class="p-4">
            <div class="h-4 bg-gray-200 mb-2" />
            <div class="h-4 bg-gray-200 w-3/4" />
          </div>
        </div>
      </div>
      
      <div v-else-if="favorites.length === 0" class="text-center py-16">
        <div class="i-mdi-heart-outline text-8xl text-gray-300 mb-4" />
        <p class="text-gray-600 mb-4">还没有收藏任何项目</p>
        <NuxtLink to="/products" class="btn-primary">
          去逛逛
        </NuxtLink>
      </div>
      
      <div v-else>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div v-for="item in favorites" :key="item.id" class="relative">
            <ProductCard :product="item.product" />
            
            <!-- 取消收藏按钮 -->
            <button
              class="absolute top-4 right-4 w-10 h-10 bg-white/90 hover:bg-white rounded-full flex items-center justify-center shadow-md transition-all z-10"
              @click="handleRemoveFavorite(item.id)"
            >
              <div class="i-mdi-heart text-red-500 text-xl" />
            </button>
          </div>
        </div>
        
        <div v-if="totalPages > 1" class="mt-8 flex justify-center">
          <div class="flex items-center space-x-2">
            <button
              class="btn-outline px-3 py-2"
              :disabled="currentPage === 1"
              @click="currentPage--"
            >
              上一页
            </button>
            <span class="text-sm text-gray-600">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button
              class="btn-outline px-3 py-2"
              :disabled="currentPage === totalPages"
              @click="currentPage++"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  middleware: 'auth',
})

const currentPage = ref(1)

const { data: response, pending, refresh } = await useFetch('/api/favorites', {
  query: computed(() => ({
    page: currentPage.value,
    pageSize: 12,
  })),
  watch: [currentPage],
})

const favorites = computed(() => response.value?.data?.items || [])
const totalPages = computed(() => response.value?.data?.pagination?.totalPages || 1)

async function handleRemoveFavorite(favoriteId: string) {
  if (!confirm('确定要取消收藏吗？')) {
    return
  }
  
  try {
    await $fetch(`/api/favorites/${favoriteId}`, {
      method: 'DELETE',
    })
    
    // 刷新列表
    refresh()
  } catch (error: any) {
    alert(error.message || '取消收藏失败')
  }
}

// SEO
useSeoMeta({
  title: '我的收藏 - 代码小库',
  robots: 'noindex',
})
</script>

